package com.example.livedatautilsdemo.helper;


import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.Map;
import java.util.WeakHashMap;

/**
 * @author: njb
 * @date: 2023/7/31 0:10
 * @desc:
 */
public class LiveDataHelper<T>extends MutableLiveData {
    private final WeakHashMap<Observer<T>, Boolean> mObservers = new WeakHashMap<>();

    @Override
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
        mObservers.put((Observer<T>) observer, true);
        super.observe(owner, observer);
    }

    @Override
    public void removeObserver(@NonNull Observer observer) {
        mObservers.remove(observer);
        super.removeObserver(observer);
    }

    @Override
    public void removeObservers(@NonNull LifecycleOwner owner) {
        mObservers.clear();
        super.removeObservers(owner);
    }

    public void setValue(Object value) {
        for (Map.Entry<Observer<T>, Boolean> entry : mObservers.entrySet()) {
            if (entry.getValue()) {
                entry.setValue(false);
                entry.getKey().onChanged((T) value);
            }
        }
    }

    public void call() {
        setValue(null);
    }
}
